﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>履历信息</span>
					</div>

					<el-row :gutter="20">
						<!-- <el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_ResumeType_FormItem" prop="Entity.ResumeType">
								<template #label>
									<WtmLabelTooltip label="履历类型" tooltip="履历类型，如调岗、晋升等" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.ResumeType" clearable class="width100"></el-input>
							</el-form-item>
						</el-col> -->
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StartDate_FormItem" prop="Entity.StartDate">
								<template #label>
									<WtmLabelTooltip label="起始日期" tooltip="履历起始日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.StartDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_EndDate_FormItem" prop="Entity.EndDate">
								<template #label>
									<WtmLabelTooltip label="结束日期" tooltip="履历结束日期" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.EndDate" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>原职位信息</span>
						<span class="title-spacer"></span>
						<el-button class="toggle-btn" type="primary" size="small" @click="toggleOriginalManual">
							{{ stateData.useOriginalManual ? '选择模式' : '手动输入' }}
						</el-button>
						<el-tooltip placement="top" content="如果在选择中找不到部门/岗位，请点击‘手动输入’后直接填写。">
							<el-icon class="tip-icon"><QuestionFilled /></el-icon>
						</el-tooltip>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20" v-if="!stateData.useOriginalManual">
							<WtmDeptSelector
								v-model:model-value="stateData.vmModel.Entity.OriginalGroupId"
								prop="Entity.OriginalGroupId"
								label="原部门"
								:auth="false"
								:rules="[]"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20" v-if="!stateData.useOriginalManual">
							<el-form-item ref="Entity_OriginalPositionId_FormItem" prop="Entity.OriginalPositionId">
								<template #label>
									<WtmLabelTooltip label="原岗位" tooltip="原岗位" />
								</template>
								<el-select
									v-model="stateData.vmModel.Entity.OriginalPositionId"
									clearable
									filterable
									class="width100"
									:disabled="!stateData.vmModel.Entity.OriginalGroupId"
								>
									<el-option
										v-for="item in stateData.AllSysJobPositionsOriginal"
										:key="item.Value"
										:value="item.Value"
										:label="item.Text"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.useOriginalManual">
							<el-form-item ref="Entity_OriginalDepartmentPosition_FormItem" prop="Entity.OriginalDepartmentPosition">
								<template #label>
									<WtmLabelTooltip label="原部门岗位" tooltip="手动输入原部门与岗位" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.OriginalDepartmentPosition" clearable placeholder="请输入“部门-岗位”"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_OriginalRank_FormItem" prop="Entity.OriginalRank">
								<template #label>
									<WtmLabelTooltip label="原职级" tooltip="原职级" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.OriginalRank" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_OriginalBaseSalary_FormItem" prop="Entity.OriginalBaseSalary">
								<template #label>
									<WtmLabelTooltip label="原基本薪资" tooltip="原基本薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.OriginalBaseSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_OriginalPositionSalary_FormItem" prop="Entity.OriginalPositionSalary">
								<template #label>
									<WtmLabelTooltip label="原岗位薪资" tooltip="原岗位薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.OriginalPositionSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_OriginalPerformanceSalary_FormItem" prop="Entity.OriginalPerformanceSalary">
								<template #label>
									<WtmLabelTooltip label="原绩效薪资" tooltip="原绩效薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.OriginalPerformanceSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>调整后信息</span>
						<span class="title-spacer"></span>
						<el-button class="toggle-btn" type="primary" size="small" @click="toggleNewManual">
							{{ stateData.useNewManual ? '选择模式' : '手动输入' }}
						</el-button>
						<el-tooltip placement="top" content="如果在选择中找不到部门/岗位，请点击‘手动输入’后直接填写。">
							<el-icon class="tip-icon"><QuestionFilled /></el-icon>
						</el-tooltip>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20" v-if="!stateData.useNewManual">
							<WtmDeptSelector
								v-model:model-value="stateData.vmModel.Entity.NewGroupId"
								prop="Entity.NewGroupId"
								label="新部门"
								:auth="false"
								:rules="[]"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20" v-if="!stateData.useNewManual">
							<el-form-item ref="Entity_NewPositionId_FormItem" prop="Entity.NewPositionId">
								<template #label>
									<WtmLabelTooltip label="新岗位" tooltip="新岗位" />
								</template>
								<el-select
									v-model="stateData.vmModel.Entity.NewPositionId"
									clearable
									filterable
									class="width100"
									:disabled="!stateData.vmModel.Entity.NewGroupId"
								>
									<el-option v-for="item in stateData.AllSysJobPositionsNew" :key="item.Value" :value="item.Value" :label="item.Text"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.useNewManual">
							<el-form-item ref="Entity_NewDepartmentPosition_FormItem" prop="Entity.NewDepartmentPosition">
								<template #label>
									<WtmLabelTooltip label="新部门岗位" tooltip="手动输入新部门与岗位" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.NewDepartmentPosition" clearable placeholder="请输入“部门-岗位”"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_NewRank_FormItem" prop="Entity.NewRank">
								<template #label>
									<WtmLabelTooltip label="新职级" tooltip="新职级" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.NewRank" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_NewBaseSalary_FormItem" prop="Entity.NewBaseSalary">
								<template #label>
									<WtmLabelTooltip label="新基本薪资" tooltip="新基本薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.NewBaseSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_NewPositionSalary_FormItem" prop="Entity.NewPositionSalary">
								<template #label>
									<WtmLabelTooltip label="新岗位薪资" tooltip="新岗位薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.NewPositionSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_NewPerformanceSalary_FormItem" prop="Entity.NewPerformanceSalary">
								<template #label>
									<WtmLabelTooltip label="新绩效薪资" tooltip="新绩效薪资" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.NewPerformanceSalary" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>履历信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_TransferReason_FormItem" prop="Entity.TransferReason">
								<template #label>
									<WtmLabelTooltip label="调整原因" tooltip="调整原因" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.TransferReason" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="履历备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, nextTick, watch } from 'vue';
import { SysPersonResumeApi as api } from '/@/views/person/syspersonresume/api';
import other from '/@/utils/other';
import { ISysPersonResumeVm } from '/@/views/person/syspersonresume/api/interface';
import { IViewModel } from '/@/types/common';
import { QuestionFilled } from '@element-plus/icons-vue';

const ci = getCurrentInstance() as any;
const loading = ref(false);
// 定义变量内容
const formRef = ref();
const stateData = reactive<
	IViewModel<ISysPersonResumeVm> & {
		AllSysJobPositionsOriginal: any[];
		AllSysJobPositionsNew: any[];
		useOriginalManual: boolean;
		useNewManual: boolean;
	}
>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			TransferRequestId: null,
			ResumeType: null,
			StartDate: null,
			EndDate: null,
			OriginalGroupId: null,
			OriginalPositionId: null,
			OriginalDepartmentPosition: null,
			OriginalRank: null,
			OriginalBaseSalary: null,
			OriginalPositionSalary: null,
			OriginalPerformanceSalary: null,
			NewGroupId: null,
			NewPositionId: null,
			NewDepartmentPosition: null,
			NewRank: null,
			NewBaseSalary: null,
			NewPositionSalary: null,
			NewPerformanceSalary: null,
			TransferReason: null,
			Remark: null,
		},
	},

	AllSysPersons: [] as any[],
	AllSysHrTransferRequestBills: [] as any[],
	AllSysGroups: [] as any[],
	AllSysJobPositions: [] as any[],
	AllSysJobPositionsOriginal: [] as any[],
	AllSysJobPositionsNew: [] as any[],
	useOriginalManual: false,
	useNewManual: false,
});

// 数据是否加载完成开关，用于防止初始化时触发watch清空回显
const dataLoaded = ref(false);

// 通用：岗位作用域配置与工具函数，避免 Original/New 重复代码
const API_ENDPOINTS = { POSITIONS: '/api/common/getjobpositions' } as const;

type PositionScope = 'Original' | 'New';
const POSITION_SCOPE_CONFIG: Record<
	PositionScope,
	{
		groupKey: 'OriginalGroupId' | 'NewGroupId';
		positionKey: 'OriginalPositionId' | 'NewPositionId';
		listKey: 'AllSysJobPositionsOriginal' | 'AllSysJobPositionsNew';
	}
> = {
	Original: { groupKey: 'OriginalGroupId', positionKey: 'OriginalPositionId', listKey: 'AllSysJobPositionsOriginal' },
	New: { groupKey: 'NewGroupId', positionKey: 'NewPositionId', listKey: 'AllSysJobPositionsNew' },
};

const buildPositionsUrl = (groupId?: string | number) => (groupId ? `${API_ENDPOINTS.POSITIONS}?groupId=${groupId}` : API_ENDPOINTS.POSITIONS);

const loadPositions = async (scope: PositionScope, groupId: any) => {
	const url = buildPositionsUrl(groupId);
	const list = await other.getSelectList(url, [], false);
	stateData[POSITION_SCOPE_CONFIG[scope].listKey] = list as any;
};

const setupScopeWatcher = (scope: PositionScope) => {
	const { groupKey, positionKey, listKey } = POSITION_SCOPE_CONFIG[scope];
	watch(
		() => (stateData.vmModel.Entity as any)[groupKey],
		(newGroupId: any, oldGroupId: any) => {
			if (dataLoaded.value && newGroupId !== oldGroupId) {
				(stateData.vmModel.Entity as any)[positionKey] = null;
				if (newGroupId) {
					loadPositions(scope, newGroupId);
				} else {
					(stateData as any)[listKey] = [];
				}
			}
		}
	);
};

// 安装通用监听器
setupScopeWatcher('Original');
setupScopeWatcher('New');

// 取消
const onClose = () => {
	closeDialog();
};

// 切换原职位信息输入模式
const toggleOriginalManual = () => {
	stateData.useOriginalManual = !stateData.useOriginalManual;
	if (stateData.useOriginalManual) {
		// 切到手动输入，清空选择器值
		stateData.vmModel.Entity.OriginalGroupId = null;
		stateData.vmModel.Entity.OriginalPositionId = null;
		stateData.AllSysJobPositionsOriginal = [];
	} else {
		// 切回选择模式，清空手动输入
		(stateData.vmModel.Entity as any).OriginalDepartmentPosition = null;
	}
};

// 切换新职位信息输入模式
const toggleNewManual = () => {
	stateData.useNewManual = !stateData.useNewManual;
	if (stateData.useNewManual) {
		stateData.vmModel.Entity.NewGroupId = null;
		stateData.vmModel.Entity.NewPositionId = null;
		stateData.AllSysJobPositionsNew = [];
	} else {
		(stateData.vmModel.Entity as any).NewDepartmentPosition = null;
	}
};

// 提交
const onSubmit = () => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			api()
				.edit(stateData.vmModel)
				.then(() => {
					ElMessage.success(ci.proxy.$t('message._system.common.vm.submittip'));
					emit('refresh');
					closeDialog();
				})
				.catch((error) => {
					other.setFormError(ci, error);
				})
				.finally(() => {
					loading.value = false;
				});
		}
	});
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	if (ci.attrs['wtmdata']) {
		stateData.vmModel.Entity.ID = ci.attrs['wtmdata'].ID;
		stateData.vmModel.Entity.PersonId = ci.attrs['wtmdata'].PersonId;
	}
	const promises: Promise<any>[] = [
		other.getSelectList('/api/SysPersonResume/GetSysHrTransferRequestBills', [], false).then((x) => {
			stateData.AllSysHrTransferRequestBills = x;
		}),

		api()
			.get(stateData.vmModel.Entity.ID ?? '')
			.then(async (data: any) => {
				other.setValue(stateData.vmModel, data);
				// 根据回显值判断默认模式
				stateData.useOriginalManual = !!stateData.vmModel.Entity.OriginalDepartmentPosition;
				stateData.useNewManual = !!stateData.vmModel.Entity.NewDepartmentPosition;
				// 数据加载完成后，根据部门ID加载对应的岗位数据
				const jobsPromises: Promise<any>[] = [];
				if (!stateData.useOriginalManual && stateData.vmModel.Entity.OriginalGroupId) {
					jobsPromises.push(loadPositions('Original', stateData.vmModel.Entity.OriginalGroupId));
				}
				if (!stateData.useNewManual && stateData.vmModel.Entity.NewGroupId) {
					jobsPromises.push(loadPositions('New', stateData.vmModel.Entity.NewGroupId));
				}
				// 等待所有岗位数据加载完成后再开启监听
				await Promise.allSettled(jobsPromises);
				// 使用 nextTick 确保 DOM 更新完成
				await nextTick();
				dataLoaded.value = true;
			}),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	});
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);
// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: ci.proxy.$t('message._system.common.vm.submit'),
			type: 'primary',
			onClick: onSubmit,
			visible: true,
		},
		{
			text: ci.proxy.$t('message._system.common.vm.cancel'),
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>

<style scoped>
.section-title {
	display: flex;
	align-items: center;
}
.title-spacer {
	flex: 1;
}
.tip-link {
	margin-left: 8px;
	color: var(--el-color-info);
	cursor: help;
}
.tip-icon {
	margin-left: 6px;
	color: var(--el-color-info);
}
.toggle-btn {
	padding: 4px 10px;
	height: 26px;
}
</style>
